package com.movie.mybatis.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        //不能拦截：
        //用户已经登陆了  session != null && session.getAttribute("user") != null
        //进入应用的cookie判断不能拦截 /welcome
        //用户访问登录页不能拦截  /index.jsp
        //登录的Servlet判断不能拦截  /user/login
        //退出系统不能拦截  /user/exit

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取请求路径
        String servletPath = request.getServletPath();
        HttpSession session = request.getSession(false);
        if("/index.jsp".equals(servletPath) || "/welcome".equals(servletPath) ||
                "/login".equals(servletPath) || "/exit".equals(servletPath)
                || (session != null && session.getAttribute("user") != null)){
            // 继续往下走
            filterChain.doFilter(request,response);
        }else{
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }
}
